package agent

import (
	"log"
	"net"
	"os"
	"os/exec"
	"os/user"

	"git.sr.ht/~sircmpwn/go-bare"
)

func GetMasterPassword(block bool) (string, error) {
	// todo memguard
	var masterPassword = ""
	var command byte
	if block {
		command = 2
	} else {
		command = 1
	}
	user, err := user.Current()
	if err != nil {
		log.Println("Error getting user ", err)
		return "", err
	}
	fileInfo, err := os.Stat("/tmp/eeze-agent-" + user.Username)
	if err == nil && fileInfo.Mode()&os.ModeSocket != 0 {
		conn, err := net.Dial("unix", "/tmp/eeze-agent-"+user.Username)
		if err != nil {
			log.Println("Warning, cannot connect to agent", err)
			return "", err
		}
		defer conn.Close()

		_, err = conn.Write([]byte{command})
		if err != nil {
			log.Println("Warning, cannot write to agent", err)
			return "", err
		}
		r := bare.NewReader(conn)
		masterPassword, err = r.ReadString()
		if err != nil {
			log.Println("Warning, cannot read from agent", err)
			return "", err
		}
	}
	return masterPassword, nil
}

// todo memguard
func GiveMasterPassword(masterPassword string) error {
	user, err := user.Current()
	if err != nil {
		log.Println("Error getting user ", err)
		return err
	}
	fileInfo, err := os.Stat("/tmp/eeze-agent-" + user.Username)
	if err == nil && fileInfo.Mode()&os.ModeSocket != 0 {
		conn, err := net.Dial("unix", "/tmp/eeze-agent-"+user.Username)
		if err != nil {
			log.Println("Warning, cannot connect to agent", err)
			return err
		}
		defer conn.Close()

		w := bare.NewWriter(conn)
		err = w.WriteU8(0)
		if err != nil {
			log.Println("Warning, cannot write cmd to agent", err)
			return err
		}
		err = w.WriteString(masterPassword)
		if err != nil {
			log.Println("Warning, cannot write password to agent", err)
			return err
		}
	}
	return nil
}

func StartAgent() {
	exec.Command("eeze-agent").Run()
}
